package com.xudow.app.dynamicstate_old.module.discovery.search;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.xudow.app.R;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by ske on 2016/6/30.
 */
public class SearchContentFragment extends Fragment {
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    PageAdapter mAdapter;
    private DynamicSearchFragment mDynamicSearchFragment;
    private UserSearchFragment mUserSearchFragment;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search_content, container, false);
        ButterKnife.bind(this, view);
        setupView();
        return view;
    }

    private void setupView() {
        mAdapter = new PageAdapter(getChildFragmentManager());
        viewpager.setAdapter(mAdapter);
        tablayout.setupWithViewPager(viewpager);
    }

    public void search(String searchText) {
        new Handler().postDelayed(() -> mDynamicSearchFragment.search(searchText),200);
        new Handler().postDelayed(() -> mUserSearchFragment.search(searchText), 400);
    }

    private class PageAdapter extends FragmentStatePagerAdapter {

        public PageAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return mDynamicSearchFragment = new DynamicSearchFragment();
                case 1:
                    return mUserSearchFragment = new UserSearchFragment();
                default:
                    return null;
            }
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "内容";
                case 1:
                    return "用户";
                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            return 2;
        }
    }
}
